package com.server;

import com.alibaba.fastjson.JSON;
import com.bean.InputHead;
import com.bean.JsonMessage;
import com.bean.Result;
import com.utils.ClassReflect;
import com.utils.CommonConst;
import com.utils.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.util.AsciiString;
import io.netty.util.CharsetUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;


public class HttpServerInboundHandler extends ChannelInboundHandlerAdapter {
    private FullHttpRequest htp;
    public static final AsciiString CLOSE = new AsciiString("close");
    private String queueName = "testQueue";
    private static Logger logger = LogManager.getLogger(HttpServerInboundHandler.class.getName());

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Result result = new Result();
        result.setStatus(CommonConst.ZREO_SHORT);
        boolean bool = false;
        boolean connect = false;
        String wxpayRes = CommonConst.BLANK;

        //这里处理逻辑，对应反射到具体control处理业务。
        if (msg instanceof FullHttpRequest) {
            try {
                htp = (FullHttpRequest) msg;
                String uri = htp.uri();
                queueName = uri.substring(1, uri.length());

                ByteBuf buf = htp.content();
                String message = buf.toString(CharsetUtil.UTF_8);
                logger.debug("message=========>" + message);

                buf.release();
                //初始化
                String head = CommonConst.BLANK;
                String body = CommonConst.BLANK;

                if ("isLiving".equals(queueName)) {
                    logger.info("httpServer is living!");
                    result.setCode(CommonConst.ONE);
                    result.setStatus(CommonConst.ONE_SHORT);
                } else if (StringUtils.isBlankOrEmpty(queueName) && StringUtils.isBlankOrEmpty(message)) {
                    logger.debug("queueName and message are both blank or null");
                    result.setCode(CommonConst.ONE);
                    result.setStatus(CommonConst.ONE_SHORT);
                } else {
                    switch (queueName) {
                        case "heartbeat":
                            //心跳服务器
                            head = "{\"reqName\":\"HeartbeatC/dead\"}";
                            body = message;
                            bool = true;
                            break;
                        default:
                            //一般情况
                            JsonMessage jsonMessage = JSON.parseObject(message, JsonMessage.class);
                            head = jsonMessage.getHead();
                            body = jsonMessage.getBody();
                            logger.info("InputHead message is: " + head);
                            logger.info("MessageBody message is: " + body);
                    }

                }
                InputHead h = JSON.parseObject(head, InputHead.class);

                // 类反射调用start
                String pg = "com.control.";

                String className = pg + h.getClassname();

                if (CommonConst.USERC.equals(h.getClassname()) && (CommonConst.LOGINOUT.equals(h.getMethodname()))) {
                    ClassReflect.classReflect(Class.forName(className), h.getMethodname(), body, result);
                } else {
//                        //token 验证
//                        JSONObject jsonObject = JSON.parseObject(body);
//                        String token = StringUtils.blankOrEmpty(jsonObject.getString(CommonConst.TOKEN_));
//                        String deviceId = StringUtils.blankOrEmpty(jsonObject.getString(CommonConst.DEVICEID_));
//                        String uId = StringUtils.blankOrEmpty(jsonObject.getString(CommonConst.UID_));
//
//                        if (CommonConst.ZERO.equals(str)) {
//                            ClassReflect.classReflect(Class.forName(className), h.getMethodname(), body, result);
//                        } else {
//                            result.setStatus(CommonConst.ONE_SHORT);
//                            result.setCode(str);
//                        }
                }


            } catch (Exception e) {
                e.printStackTrace();
                logger.error("HttpServerInboundHandler error is try{}====>", e.getMessage());
                result.setCode(CommonConst.ONE);
                result.setStatus(CommonConst.ONE_SHORT);
            }

            String returnResult;
            if (!StringUtils.isBlankOrEmpty(wxpayRes)) {
                returnResult = wxpayRes;
            } else {
                returnResult = JSON.toJSONString(result);
            }

            logger.debug(queueName + " result is: " + returnResult);
            FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                    OK, Unpooled.wrappedBuffer(returnResult.getBytes("UTF-8")));
            response.headers().set(CONTENT_TYPE, "text/plain");
            response.headers().setInt(CONTENT_LENGTH,
                    response.content().readableBytes());
            response.headers().set("Access-Control-Allow-Origin", "*");
//            if (HttpHeaderUtil.isKeepAlive(htp)) {//判断是否活着
//                response.headers().set(CONNECTION, KEEP_ALIVE);
//            }
            if (bool || connect) {
                response.headers().set(CONNECTION, CLOSE);
            }

            ctx.write(response);
            ctx.flush();

        } else {
            logger.debug("---------------未执行-----------------");
        }
        logger.debug("-----------------------------------");
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        logger.error("HttpServerInboundHandler.exceptionCaught error===>",cause.getMessage());
        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
}
